package com.easyfun.healthmagicbox.sync;


import com.easyfun.healthmagicbox.HMBMainActivity;
import com.easyfun.healthmagicbox.R;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class HealthService  extends Service
	{
		private final static String TAG = "MyService";
		private NotificationManager notificationMgr;   
		
		//用于和外界交互
		private final IBinder binder = new MyBinder();

		public class MyBinder extends Binder
		{
			HealthService getService()
			{
				return HealthService.this;
			}
		}

		@Override
		public void onCreate()
		{
			SyncManager.initialize(this);
			Thread thr = new Thread(null, SyncManager.getInstance(), "BackgroundSercie");   
			thr.start();  
			super.onCreate();
		}
		
		@Override
		public IBinder onBind(Intent intent)
		{
			Log.d(TAG, String.format("on bind,intent = %s", intent.toString()));
			notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   
			displayNotificationMessage("服务已绑定");   

			return binder;
		}
		
		@Override
		public int onStartCommand(Intent intent, int flags, int startId)
		{
			if (intent!=null)
			{
				Log.d(TAG, "start action="+intent.getAction());
				notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   
				displayNotificationMessage("运行中", true);   
			}
			return super.onStartCommand(intent, flags, startId);
		}

		@Override
		public void onDestroy()
		{
			notificationMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   
			displayNotificationMessage("已关闭", true);
			stopForeground(true);
			SyncManager.getInstance().stop();
			super.onDestroy();
		}

		
		
		//为服务设置图标和文字描述
		public void displayNotificationMessage(String message, boolean isForeground)
		{   
			
			Notification notification = new Notification(R.drawable.ic_launcher, message,   
					System.currentTimeMillis());   
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,   
					new Intent(this, HMBMainActivity.class), 0);   
			notification.setLatestEventInfo(this, "健康盒子", message,   
					contentIntent);   
			HealthService.this.startForeground(R.id.app_notification_id, notification);
		}   
		
		public void displayNotificationMessage(String message)
		{   
			Notification notification = new Notification(R.drawable.ic_launcher, message,   
					System.currentTimeMillis());   
			PendingIntent contentIntent = PendingIntent.getActivity(this, 0,   
					new Intent(this, HMBMainActivity.class), 0);   
			notification.setLatestEventInfo(this, "我的通知", message,   
					contentIntent);   
			notificationMgr.notify(R.id.app_notification_id + 1, notification);  
		}   
		
		
	
}
